#region Copyright

// The contents of this file are subject to the Mozilla Public License
//  Version 1.1 (the "License"); you may not use this file except in compliance
//  with the License. You may obtain a copy of the License at
//  
//  http://www.mozilla.org/MPL/
//  
//  Software distributed under the License is distributed on an "AS IS"
//  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
//  License for the specific language governing rights and limitations under 
//  the License.
//  
//  The Initial Developer of the Original Code is Robert Smyth.
//  Portions created by Robert Smyth are Copyright (C) 2008.
//  
//  All Rights Reserved.

#endregion

using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using NUnitGrid.Framework;
using NUnitGrid.Framework.Logging;


namespace NUnitGrid.Node.Runner
{
    public class AsynchronousProcessRunner : IScheduledEventListener
    {
        private readonly string arguments;
        private readonly string fileName;
        private readonly IProcessCompletedListener listener;
        private readonly ILogger logger;
        private readonly StringBuilder output = new StringBuilder();
        private readonly TimeSpan runTimeLimit;
        private readonly ISchedule schedule;
        private readonly string workingDirectory;
        private Stopwatch fixtureStopwatch;
        private Process process;
        private int threadResultCode;

        public AsynchronousProcessRunner(string workingDirectory, string fileName, string arguments, ISchedule schedule,
                                         TimeSpan runTimeLimit, IProcessCompletedListener listener, ILogger logger)
        {
            this.workingDirectory = workingDirectory;
            this.fileName = fileName;
            this.arguments = arguments;
            this.schedule = schedule;
            this.runTimeLimit = runTimeLimit;
            this.listener = listener;
            this.logger = logger;
        }

        public void Start()
        {
            threadResultCode = -1002;

            try
            {
                fixtureStopwatch = new Stopwatch();
                fixtureStopwatch.Start();

                var startInfo = new ProcessStartInfo
                                    {
                                        Verb = "runas",
                                        WorkingDirectory = workingDirectory,
                                        FileName = Path.Combine(workingDirectory, fileName),
                                        Arguments = arguments,
                                        UseShellExecute = false,
                                        RedirectStandardOutput = true,
                                        RedirectStandardError = true,
                                        ErrorDialog = false
                                    };

                process = new Process {StartInfo = startInfo};

                process.OutputDataReceived += process_OutputDataReceived;
                process.ErrorDataReceived += process_OutputDataReceived;

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                schedule.AddEvent(this, TimeSpan.FromMilliseconds(50));
            }
            catch (Exception exception)
            {
                output.AppendLine(
                    string.Format(
                        @"Exception thrown running '{0}' with command line '{1}'.\n\nException: {2}\nStack: {3}",
                        fileName, arguments, exception.Message, exception.StackTrace));

                listener.OnCompleted(threadResultCode, output.ToString());
            }
        }

        void IScheduledEventListener.OnEventFired()
        {
            if (process.HasExited || !process.Responding || fixtureStopwatch.Elapsed >= runTimeLimit)
            {
                if (fixtureStopwatch.Elapsed >= runTimeLimit)
                {
                    logger.Warning.Write("Task timeout. Aborting task.");
                    output.AppendLine("\nGrid runner timeout. Aborting.\n");
                    process.Kill();
                    process.WaitForExit(5000);
                }

                threadResultCode = process.HasExited ? process.ExitCode : -10001;

                if (threadResultCode != 0)
                {
                    var message = string.Format("Error: NUnit returned error code {0}.", threadResultCode);
                    logger.Warning.Write(message);
                    output.AppendLine(message);
                }

                listener.OnCompleted(threadResultCode, output.ToString());
            }
            else
            {
                schedule.AddEvent(this, TimeSpan.FromMilliseconds(50));
            }
        }

        private void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            output.AppendLine(e.Data);
        }
    }
}